<template>
  <div class="goods-recharge">
    <cell-group>
      <!-- <field v-if="orderNumber" v-model="balance" label-width="100px" label="当前余额：" readonly  />
      <field v-if="orderNumber" v-model="goodsMoney" label-width="100px" label="当前货款：" readonly  />
      
      <field v-if="orderNumber" v-model="orderNumber" label-width="100px" label="订单编号：" readonly/>
      <field v-if="orderNumber" v-model="orderDetail.orderInfo.dealTime" label-width="100px" label="下单时间：" readonly/>-->

      <field
        v-model="selectedPayType.name"
        label-width="100px"
        label="打款方式："
        readonly
        right-icon="arrow-down"
        @click="popupType = 'payType', showPopup = true"
      />

      <field
        v-if="selectedPayType.id == 2"
        v-model="bankName"
        label-width="100px"
        label="银行名称："
        placeholder="请输入银行名称"
      />
      <field
        v-if="selectedPayType.id == 2"
        v-model="accountName"
        label-width="100px"
        label="开户实名："
        placeholder="请输入开户实名"
      />
      <field
        v-if="selectedPayType.id == 2"
        v-model="account"
        label-width="100px"
        label="银行卡账号："
        type="number"
        placeholder="请输入你的银行卡账号"
      />
      <field
        v-if="selectedPayType.id == 1"
        v-model="account"
        label-width="100px"
        label="支付宝账号："
        placeholder="请输入你的支付宝账号"
      />

      <!-- <field v-if="orderNumber" v-model="orderDetail.orderInfo.orderMoney" label-width="100px" label="金额：" placeholder="请输入打款金额" type='number' readonly/> -->
      <field
        v-model="payMoney"
        label-width="100px"
        label="金额："
        placeholder="请输入充值金额"
        type="number"
      />

      <!-- @click="popupType = 'date', showPopup = true" -->
      <field
        v-model="time"
        label-width="100px"
        label="打款日期："
        readonly
        right-icon="arrow-down"
        @click="popupType = 'date', showPopup = true"
      />

      <field v-model="remark" label-width="100px" label="备注：" placeholder="如有说明可填写备注" />

      <div class="upload-proof">
        <div class="upload-proof-text">
          打款凭证
          <br />(1-3张)：
        </div>
        <uploader
          :max-count="3"
          v-model="payImgList"
          :after-read="afterRead"
          :max-size="imgMaxSize"
          @oversize="oversize"
        />
      </div>
    </cell-group>

    <pay-info :type="selectedPayType.id"></pay-info>

    <div class="submit">
      <van-button
        type="info"
        size="large"
        @click="recharge"
        :disabled="isSubmitting"
      >{{isSubmitting ? '正在提交' : '确认充值'}}</van-button>
    </div>

    <popup :show="showPopup" @onCancel="onCancel">
      <div v-if="popupType == 'payType'">
        <picker
          @cancel="onCancel"
          value-key="name"
          show-toolbar
          :default-index="selectedPayType.id - 1"
          :columns="payTypeList"
          @confirm="onConfirm"
        />
      </div>
      <div v-if="popupType == 'date'">
        <datetime-picker
          v-model="currentDate"
          type="date"
          :max-date="maxDate"
          :formatter="formatter"
          @confirm="onConfirm"
          @cancel="onCancel"
        />
      </div>
    </popup>
  </div>
</template>

<script>
import {
  Field,
  Cell,
  CellGroup,
  Uploader,
  Button,
  Picker,
  Toast,
  DatetimePicker
} from "vant";
import payInfo from "../components/pay_info.vue";
import popup from "../components/popup.vue";
var moment = require("moment");
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import {
  getImageMetaInfo,
  getImageAfterCompressFromCanvas,
  getImageAfterCompressBatch,
  getImageAfterCompressFromImgzip
} from "../service/imageCompress.js";
import { mapState } from "vuex";
import imgMaxSize from "../mixins/img_maxsize.js";

export default {
  components: {
    Field,
    Cell,
    CellGroup,
    Uploader,
    vanButton: Button,
    payInfo,
    popup,
    Picker,
    DatetimePicker
  },
  mixins: [imgMaxSize],
  data() {
    return {
      goodsMoney: "",
      balance: "",
      agentInfo: {},
      orderDetail: {},
      orderNumber: this.$route.query.orderNumber || "",
      showPopup: false,
      selectedPayType: {
        id: 1,
        name: "支付宝"
      },
      payTypeList: [
        {
          id: 1,
          name: "支付宝"
        },
        {
          id: 2,
          name: "银行转账"
        }
      ],
      agencyLevelList: [
        {
          id: 0,
          level_name: "全部"
        }
      ],
      selectedAgencyLevel: {
        id: 0,
        level_name: "全部"
      },
      popupType: "",
      account: "",
      bankName: "",
      accountName: "",
      payMoney: "",
      remark: "",
      payImgList: [],
      time: moment(new Date()).format("YYYY年MM月DD日"),
      currentDate: new Date(),
      isSubmitting: false
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    })
  },
  async mounted() {
    // if(this.orderNumber){
    //   let data = {
    //     title: "订单支付"
    //   };
    //   this.$store.commit("setNavInfo", data);
    //   document.title = data.title + " - TIMELESS 分销商城";
    //   await this.getAgentInfo()
    //   await this.getOrderDetail()
    // }
  },
  methods: {
    // 从订单详情跳过来时 根据订单号获取订单信息
    // getOrderDetail() {
    //   return this.$http
    //     .post(this.$urls.GJDDHHQ, {
    //       orderNum: this.orderNumber
    //     })
    //     .then(res => {
    //       if (res.data.code == 200) {
    //         this.orderDetail = res.data.data;
    //       }
    //     });
    // },

    // 货款充值  订单支付
    async recharge() {
      // 测试图片压缩
      // let r = await getImageAfterCompressFromCanvas(applyInfo.payImage[0])
      // let r = await getImageAfterCompressFromImgzip(this.payImgList[0].file)
      // console.log("图片：", r)

      let applyInfo = {
        account: this.account,
        payMoney: Number(this.payMoney),
        remark: this.remark,
        payImage: this.payImgList.length
          ? [...this.payImgList].map(item => item.content)
          : "",
        // handDocuments: [...this.handImgList].map(item => item.content),
        // agentLevel: this.selectedAgencyLevel.id,
        payType: this.selectedPayType.id,
        payTime: moment(this.currentDate).format("YYYY-MM-DD"),
        applyType: 3
      };

      // 未支付订单货款支付时
      // if(this.orderNumber){
      //   applyInfo = Object.assign({}, applyInfo, {
      //     payMoney: this.orderDetail.orderInfo.orderMoney,
      //     orderNum: this.orderNumber
      //   })
      // }

      let verify = {
        payMoney: "金额",
        account: "账户",
        payImage: "打款凭证"
        // handDocuments: "手持证"
      };

      // 打款方式为 银行卡时
      if (this.selectedPayType.id == 2) {
        applyInfo = Object.assign({}, applyInfo, {
          bankName: this.bankName,
          accountName: this.accountName
        });

        verify = Object.assign({}, verify, {
          bankName: "银行名称",
          accountName: "开户名称"
        });
      }

      for (let item in applyInfo) {
        if (!applyInfo[item]) {
          if (item in verify) {
            // console.log(item);
            Toast(verify[item] + "不能为空");
            return false;
          }
        }
      }

      // console.log(applyInfo)

      if (this.isSubmitting) {
        Toast("正在提交，请稍等");
        return false;
      }

      // 测试
      // 测试图片压缩
      // console.log(applyInfo)
      // let a = [];
      // for(let i = 0;applyInfo.payImage.length; i++){

      // }
      let payImages = await getImageAfterCompressBatch(applyInfo.payImage);
      applyInfo.payImage = payImages;
      // // let r = await getImageAfterCompressFromImgzip(this.payImgList[0].file)
      // console.log("图片：", s)
      // return false;

      // Toast('正在提交，请稍等')
      this.isSubmitting = true;

      http.post(urls.TJDLSQ, applyInfo).then(res => {
        this.isSubmitting = false;
        if (res.data.code == 200) {
          let data = res.data.data;

          Toast.success("充值申请成功");

          setTimeout(() => {
            this.$router.go(-1);
          }, 1000);
          // resolve();
        }
      });
    },
    // getAgentInfo() {
    //   return http
    //     .post(urls.DLXQ, {
    //       id: this.userInfo.id
    //     })
    //     .then(res => {
    //       if (res.data.code == 200) {
    //         let data = res.data.data;
    //         this.agentInfo = data

    //         this.goodsMoney = "￥"+this.agentInfo.goods_money
    //         this.balance = "￥"+this.agentInfo.balance
    //       }
    //     });
    // },
    // 时间格式化
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      }
      return value;
    },
    afterRead(file) {
      console.log(file);
      // this.filesList.push({url: file.content})
    },
    onCancel() {
      this.showPopup = false;
    },
    onConfirm(value) {
      if (this.popupType == "payType") {
        this.selectedPayType = value;
      } else if (this.popupType == "date") {
        this.time = moment(value).format("YYYY年MM月DD日");
        this.currentDate = value;
      }
      this.showPopup = false;
      // this.pageNumber = 1
      // this.allList = []

      // this.loading = false
      // this.finished = false
    }
  }
};
</script>

<style scoped>
.upload-proof {
  padding: 10px 15px;
  display: flex;
}

.upload-proof-text {
  /* padding-right: 10px; */
  color: #323233;
  width: 100px;
  text-align: left;
}

.tip {
  padding: 10px 15px;
  background-color: #fff;
}

.tip p {
  margin-bottom: 5px;
}

.submit {
  margin-bottom: 40px;
}
</style>